package io.xccit.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @author CH_ywx
 * @date 2023-06-05
 * @description
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;//数据源

    /**
     * @return 操作token的对象
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);//设置数据源
//        tokenRepository.setCreateTableOnStartup(true);  //自动创建表,第一次使用时执行,后面就不需要再执行
        return tokenRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/hello").permitAll();

        http.formLogin().loginPage("/login.html").loginProcessingUrl("/login") //配置登录页面
                .defaultSuccessUrl("/index")
                .permitAll().and()
                .authorizeRequests().antMatchers("/", "/hello").permitAll()//不需要权限认证即可访问的路径
                .anyRequest().authenticated();//其他路径都需要权限认证
        http.rememberMe() //配置记住我功能
                .tokenRepository(persistentTokenRepository()) //操作token的对象
                .tokenValiditySeconds(60). //60秒免登录
                userDetailsService(userDetailsService); //指定使用的userDetailsService
        http.csrf().disable(); //关闭csrf保护
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
